import services from '@/services/nginx';
import type {ActionType} from '@ant-design/pro-components';
import {PageContainer, ProList} from '@ant-design/pro-components';
import {useNavigate} from '@umijs/max';
import {message, Spin} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {useLocation, useParams} from 'react-router-dom';

const {domains} = services.DomainParsingRecordController;


interface DataSourceItem {
    name: string;
    desc: string;
    content: { label: string; value: any; }[];
}



const TableList: React.FC<unknown> = () => {
    const action = useRef<ActionType>();
    const navigate = useNavigate();
    // 数据加载等待
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);


    // 地址栏参数
    const { accessId } = useParams();
    // 确保accessId不是undefined
    const accessIdForRequest = accessId !== undefined ? accessId as unknown as string: '';

    const location = useLocation();
    const searchParams = new URLSearchParams(location.search);
    const backupName = searchParams.get('name');
    // 列表数据
    const [dataSource, setDataSource] = useState<DataSourceItem[] | undefined>(undefined);

       // 初始化数据
       useEffect(() => {
          fetchData();
        }, []);

    const fetchData = async() => {
      setLoading(true);
      setError(null);
      try {
          const response = await domains(accessIdForRequest);
          if( Array.isArray(response.data)){
              const datas = response.data.filter(item => item !== null) as API.DnsDomain[];
              // 转换函数
              const listOfNewItems:DataSourceItem[] = datas.map(item => {
                  return  {
                      name: item.domain,
                      desc: item.domainId,
                      content: [
                        {
                            label: '解析记录数',
                            value: item.recordCount
                        },
                        {
                            label: '所属厂商',
                            value: item.cloud
                        }
                     ],
                  };
              });
              setDataSource(listOfNewItems)
          }
      } catch (error) {
          setError('Failed to fetch backup files. Please try again later.');
          message.error('Failed to fetch backup files');
      } finally {
          setLoading(false);
      }
    };
    if (loading) {
      return <Spin size="large" tip="Loading backup files..." />;
    }
    if (error) {
      return <div>{error}</div>;
    }
    return (
        <PageContainer
            header={{
                title: <span>
                    〔<span style={{ color: 'red'  }}>{backupName}</span>〕域名解析
                 </span>
            }}
        >
            <ProList<any>
                rowKey="name"
                actionRef={action}
                dataSource={dataSource}
                editable={{}}
                metas={{
                title: {
                    dataIndex: 'name',
                    valueType: 'select',
                },
                description: {
                    key: 'desc',
                },
                content: {
                    dataIndex: 'content',
                    render: (text) => (
                    <div
                        key="label"
                        style={{ display: 'flex', justifyContent: 'space-around' }}
                    >
                        {(text as any[]).map((t) => (
                        <div key={t.label}>
                            <div>{t.label}</div>
                            <div>
                            {t.value}
                            </div>
                        </div>
                        ))}
                    </div>
                    ),
                },
                actions: {
                    render: (text, row) => [
                    <a
                        target="_blank"
                        rel="noopener noreferrer"
                        key="download"
                        onClick={async () => {
                            const url = `/nginx/cloudAccess/dpr/${row.name}`;
                            navigate(url, { state: {
                                'accessId':accessId,
                                domain: row.name,
                                domainId: row.desc,
                                recordCount: row.content[0].value,
                                cloud: row.content[1].value,
                            } });
                        }}
                    >
                        解析设置
                    </a>
                    ],
                },
                }}
            />
             {/* Display download progress in a modal */}
            {/*<Modal open={isDownloading} footer={null} closable={false}>*/}
            {/*    <Progress percent={progress} />*/}
            {/*</Modal>*/}
        </PageContainer>
    );
}

export default TableList;
